package com.example.demo.controller;


import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;

@Controller
public class FileOptionController {


    @GetMapping("/toUploadPage")
    public String toUploadPage() {
        return "page/upload";
    }

    @GetMapping("/toDownloadPage")
    public String toDownloadPage() {
        return "page/download";
    }


    @PostMapping("/uploadFile")
    public String uploadFile(MultipartFile[] fileUpload, Model model) {
        model.addAttribute("uploadStatus", "上传成功");
        for (MultipartFile file :
                fileUpload) {
            String filename = file.getOriginalFilename();//取得文件名
            // E:\备份\【课表】软件3月份课表-胡昆.xlsx
            //提取文件名1，拿到文件的名字和后缀的开始下标
            int index = filename.lastIndexOf("\\");
            //2,通过下标截取文件名
            filename = filename.substring(index + 1);
            //防止重名
            //3,得到新的文件名
            filename = UUID.randomUUID() + "_" + filename;
            String dirPath = "c:/file/";
            File filePath = new File(dirPath);
            if (!filePath.exists()) //判断系统有没有这个文件夹
            {
                filePath.mkdirs();//创建文件夹
            }
            try {
                file.transferTo(new File(dirPath + filename));
            } catch (IOException e) {
                e.printStackTrace();
                model.addAttribute("uploadStatus", "上传失败");
            }
        }

        return "page/upload";
    }


    @GetMapping("/download")
    public ResponseEntity<byte[]> fileDownload( HttpServletRequest request ,String filename) throws Exception {
        //目标文件
        String dirPath = "D:/fujian/";
        //String dirPath="D:\\fujian\\";

        File file = new File(dirPath + File.separator + filename);
        HttpHeaders httpHeaders = new HttpHeaders();

        filename = getFilename(request,filename);
        httpHeaders.setContentDispositionFormData("attachment", filename);
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            return new ResponseEntity<>(FileUtils.readFileToByteArray(file), httpHeaders, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<byte[]>(e.getMessage().getBytes(), HttpStatus.EXPECTATION_FAILED);
        }

    }

    /**
     * 针对中文文件名的下载的解决方案
     * @param request
     * @param filename
     * @return
     * @throws Exception
     */

    private String getFilename(HttpServletRequest request, String filename)
            throws Exception {
        String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"};
        String userAgent = request.getHeader("User-Agent");
        for (String keyWord : IEBrowserKeyWords) {
            if (userAgent.contains(keyWord)) {
                return URLEncoder.encode(filename, "UTF-8").replace("+"," ");
            }}
        return new String(filename.getBytes("UTF-8"), "ISO-8859-1");
    }


}
